/* 订单详情页 */

import api from '../../utils/http.js'

Page({

  data: {
    orders: {}, //订单详情 
  },

  onLoad(options) {
    this.setData({ order_id: options.order_id })
  },

  onShow() {
    // 订单详情
    this.getOrderDetail()
  },

  // 跳转到聊天页
  toChatPage() {
    let { id, nickname, avatar } = this.data.orders.master
    wx.navigateTo({
      url: `/pages/chat/chat?yourId=${id}&yourName=${nickname}&yourAvatar=${avatar}`,
      success: () => {
        // 移除未读消息数
        let userId = wx.getStorageSync('userId')
        wx.removeStorageSync(id + 'and' + userId + '-num')
      }
    })
  },

  // 立即支付 
  pay() {
    wx.showModal({
      content: '确定支付吗?',
      success: res => {
        if (res.confirm) {
          // 立即支付 
          api.payment(this.data.orders.order_id, { type: 3 }, { authorization: `Bearer ${wx.getStorageSync('token')}` }).then(res => {
            if (res.statusCode === 200) {
              console.log('立即支付', res)  //支付成功

              // 订单详情
              this.getOrderDetail()
            } 
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }, 

  // 取消订单
  cancelOrder(){
    wx.navigateTo({
      url: `/pages/cancelOrder/cancelOrder?order_id=${this.data.orders.order_id}`,
    })
  },

  // 用户同意开始订单
  start(){
    api.agreeStart(this.data.order_id).then(res => {
      if (res.statusCode === 200) {
        console.log('用户同意开始订单', res)

        wx.showToast({ title: res.data.message })
        
        // 订单详情
        this.getOrderDetail()
      }
    })
  },

  // 用户拒绝开始订单
  refuse(){
    api.rejectOrder(this.data.order_id).then(res => {
      if (res.statusCode === 200) {
        console.log('用户拒绝开始订单', res)

        wx.showToast({ title: res.data.message })

        // 订单详情
        this.getOrderDetail()
      }
    })
  },

  // 用户确认完成订单
  finish(){
    api.completeOrder(this.data.order_id).then(res => {
      if (res.statusCode === 200) {
        console.log('用户确认完成订单', res)
        wx.showToast({ title: res.data.message })
        
        // 订单详情
        this.getOrderDetail()
      }
    })
  },

  // 用户发起退款申请
  refund(){
    api.refund(this.data.order_id).then(res => {
      if (res.statusCode === 200) {
        console.log('用户发起退款申请', res)

        wx.showToast({ title: res.data.message })

        // 订单详情
        this.getOrderDetail()
      }
    })
  },

  // 订单详情
  getOrderDetail(){
    api.getOrderDetail(this.data.order_id).then(res => {
      console.log('订单详情', res.data.data)

      this.setData({ orders: res.data.data })
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    if (prevPage.route === "pages/placeOrder/placeOrder") wx.navigateBack({ delta: 1 })
  },
})